﻿<%@ Application Language="C#" %>

<script runat="server">

    void Application_Start(object sender, EventArgs e) 
    {
        string count = getHitsCount();
        Application["SessionCounter"] = count;
    }
    
    void Application_End(object sender, EventArgs e) 
    {
        System.Data.SqlClient.SqlConnection myConnection = new System.Data.SqlClient.SqlConnection(getSqlConnectionString());
        myConnection.Open();

        // Insert into database
        try
        {
            System.Data.SqlClient.SqlCommand myCommand = new System.Data.SqlClient.SqlCommand("UPDATE SiteHits SET SiteHits = '" + Application["SessionCounter"] + "' WHERE Id = 1", myConnection);
            myCommand.ExecuteNonQuery();
        }
        catch (Exception)
        {

        }

        myConnection.Close();
    }

    void Session_Start(object sender, EventArgs e) 
    {
        string counter_string = "0";
        try
        {
            counter_string = Application["SessionCounter"].ToString();
        }
        catch
        {
            counter_string = getHitsCount();
        }
        /*
        if (counter_string != null)
        {
            try
            {
                int counter = Int32.Parse(Application["SessionCounter"].ToString());
                Application["SessionCounter"] = counter + 1;
            }
            catch (Exception)
            {
                Application["SessionCounter"] = 0;
            }
        }
        */
    }

    /// <summary>
    /// Database connection string
    /// </summary>
    /// <returns>String representation of database connection string</returns>
    private static string getSqlConnectionString()
    {
        string strConnString = ConfigurationManager.ConnectionStrings["dbConnectionString"].ConnectionString;
        return @strConnString;
    }

    private string getHitsCount()
    {
        // Connect to local database
        String sql_connection = getSqlConnectionString();
        System.Data.SqlClient.SqlConnection myConnection = new System.Data.SqlClient.SqlConnection(sql_connection);
        myConnection.Open();

        string count = "0";

        // Retrieve assessment information from database
        try
        {
            System.Data.SqlClient.SqlDataReader myReader = null;
            System.Data.SqlClient.SqlCommand myCommand = new System.Data.SqlClient.SqlCommand("SELECT SiteHits FROM SiteHits WHERE Id = '1'", myConnection);
            myReader = myCommand.ExecuteReader();
            while (myReader.Read())
            {
                count = myReader["SiteHits"].ToString();
            }
            myReader.Close();
        }
        catch (Exception ex)
        {

        }
        myConnection.Close();

        return count;
    }
</script>
